import { Checkbox, DatePicker, Form, Input, Space, Toast } from 'antd-mobile';
import { useEffect, useState } from 'react';
import HeadTitle from '../../components/headtitle';
import MainContainer from '../../components/maincontainer';
import Container from '../../components/container';
import GroupTitle from '../../components/grouptitle';
import GroupTitleByupdown from '../../components/grouptitlebyupdown';
import LeftLbl from './leftlbl';
import Infocontainer from './infocontainer';
import pages from '../../atoms/pages';
import GetUserInfo from '../../atoms/userinfo';
import DateConvert from '../../atoms/date';
import uuid from '../../atoms/uuid';
import { Message as M1, Result as R1 } from '../api/activity/addlaunch.api';
import { IData as D2, Query as Q2, Result as R2 } from '../api/activity/avtivity.api';
import { Query as Q3, Result as R3 } from '../api/activity/fielddata.api';
import api from '../../atoms/api';
import Btn from '../../components/btn';
import smartfetch from '../../atoms/smartfetch';

export default function Content({ aid }: { aid: string }) {
	//用户
	const user = GetUserInfo();
	//标题
	const title = aid ? '修改报名信息' : '发起新报名';
	//数据
	const [newid, setNewid] = useState(aid);
	const now = Date.now();
	const [data, setData] = useState({
		aid,
		theme: '',
		userid: user.userid,
		username: user.username,
		place: '',
		starttime: now,
		endtime: now,
		bytime: now,
		maxnumber: 40,
		cost: 100,
		explain: '',
		isforward: 0,
		iscancel: 0,
		state: 1,
		url: '',
		qrcode: '/images/qr.png'
	} as M1);
	//更新数据
	function SetDataValue(field: keyof M1, value: string | number) {
		setData((origin) => {
			return {
				...origin,
				[field]: value
			};
		});
	}

	//日期展示
	function GetDate(d: number) {
		return new Date(d);
	}
	const [startVisible, setStartVisible] = useState(false);
	const [endVisible, setEndVisible] = useState(false);
	const [byVisible, setByVisible] = useState(false);
	//报名要求
	const [direction, setDirection] = useState(true);
	const [name, setName] = useState(true);
	const [id, setId] = useState(false);
	const [phone, setPhone] = useState(true);
	const [work, setWork] = useState(false);
	const [snum, setSNum] = useState(false);
	const [isTo, setIsTo] = useState(false);
	const [isCancel, setIsCancel] = useState(false);

	//保存活动信息
	async function Save(state?: number) {
		if (!data.theme) {
			Toast.show({
				content: '活动主题不能为空！',
				position: 'center',
				icon: 'fail'
			});
			return '';
		}
		//调用保存服务
		let result;
		if (aid) {
			//修改状态
			const s = state ? state : 2;
			SetDataValue('state', s);
			//修改
			result = await smartfetch<R1, M1>(api['/api/activity/editlaunch'], 'post', { ...data, state: s });
		}
		else {
			//修改状态
			const s = state ? state : 1;
			SetDataValue('state', s);
			//新增
			const id = uuid();
			setNewid(id);
			SetDataValue('aid', id);
			result = await smartfetch<R1, M1>(api['/api/activity/addlaunch'], 'post', { ...data, aid: id, state: s });
		}
		console.log(result);
		if (result.ok) {
			Toast.show({
				content: '保存成功！',
				position: 'center',
				icon: 'success'
			});
		}
		else {
			Toast.show({
				content: result.message,
				position: 'center',
				icon: 'fail'
			});
		}
		return aid || newid;
	}

	//执行
	useEffect(() => {
		void (async () => {
			//获取数据
			if (aid) {
				const d = await smartfetch<R2, Q2>(api['/api/activity/avtivity'], 'get', { aid });
				if (d) {
					setData(d.data);
				}
			}
		})();
	}, [aid]);
	return <>
		<MainContainer>
			<HeadTitle title={title} url={pages['/']} />
			<Container>
				<GroupTitle title='基本信息' />
				{/* <Form layout='horizontal'>
						<Form.Item name='theme' required label='活动主题：'>
							<Input className='in' placeholder='请输入活动主题' />
						</Form.Item>
						<Form.Item name='initiator' required label='发起人：'>
							<Input className='in' placeholder='请输入发起人' />
						</Form.Item>
					</Form> */}
				{/* 活动主题 */}
				<Infocontainer >
					<LeftLbl title='活动主题' required />
					<input className='inp' type='text' value={data.theme} maxLength={20} placeholder='请输入活动主题' onChange={(e) => {
						SetDataValue('theme', e.target.value);
					}} />
				</Infocontainer>
				{/* 发起人 */}
				<Infocontainer >
					<LeftLbl title='发起人' />
					<input className='inp' value={data.username} type='text' maxLength={20} placeholder='请输入发起人' onChange={(e) => {
						SetDataValue('username', e.target.value);
					}} />
				</Infocontainer>
				{/* 活动地点 */}
				<Infocontainer >
					<LeftLbl title='活动地点' />
					<input className='inp' value={data.place} type='text' maxLength={30} placeholder='请输入活动地点' onChange={(e) => {
						SetDataValue('place', e.target.value);
					}} />
				</Infocontainer>
				{/* 活动开始时间 */}
				<Infocontainer >
					<LeftLbl title='活动开始时间' />
					<input readOnly className='inp' value={DateConvert(Number(data.starttime))} placeholder='时间日期选择' onClick={() => {
						setStartVisible(true);
					}} />
					<DatePicker
						title='时间选择'
						visible={startVisible}
						onClose={() => {
							setStartVisible(false);
						}}
						defaultValue={GetDate(data.starttime)}
						min={GetDate(data.starttime)}
						onConfirm={val => {
							SetDataValue('starttime', val.valueOf());
							if (DateComper(val, data.endtime)) {
								SetDataValue('endtime', val.valueOf());
								SetDataValue('bytime', val.valueOf());
							}
						}}
					/>
				</Infocontainer>
				{/* 活动结束时间 */}
				<Infocontainer >
					<LeftLbl title='活动结束时间' />
					<input readOnly className='inp' value={DateConvert(Number(data.endtime))} placeholder='时间日期选择' onClick={() => {
						setEndVisible(true);
					}} />
					<DatePicker
						title='时间选择'
						visible={endVisible}
						onClose={() => {
							setEndVisible(false);
						}}
						defaultValue={GetDate(data.endtime)}
						min={GetDate(data.starttime)}
						onConfirm={val => {
							SetDataValue('endtime', val.valueOf());
						}}
					/>
				</Infocontainer>
				{/* 报名截止时间 */}
				<Infocontainer >
					<LeftLbl title='报名截止时间' />
					<input readOnly className='inp' value={DateConvert(Number(data.bytime))} placeholder='时间日期选择' onClick={() => {
						setByVisible(true);
					}} />
					<DatePicker
						title='时间选择'
						visible={byVisible}
						onClose={() => {
							setByVisible(false);
						}}
						defaultValue={GetDate(data.bytime)}
						min={GetDate(data.starttime)}
						max={GetDate(data.endtime)}
						onConfirm={val => {
							SetDataValue('bytime', val.valueOf());
						}}
					/>
				</Infocontainer>
				{/* 商家入驻上限 */}
				<Infocontainer >
					<LeftLbl title='商家入驻上限' />
					<input className='inp' type='number' value={data.maxnumber?.toString()} placeholder='请输入报名人数上限' onChange={(e) => {
						SetDataValue('maxnumber', parseInt(e.target.value));
					}} />
				</Infocontainer>
				{/* 活动费用
				<Infocontainer >
					<LeftLbl title='活动费用' />
					<input className='inp' type='number' value={data.cost?.toString()} placeholder='请输入活动费用' onChange={(e) => {
						SetDataValue('cost', parseInt(e.target.value));
					}} />
				</Infocontainer>
				{/* 活动说明 */}
				{/* <Infocontainer >
					<LeftLbl title='活动说明' />
					<textarea className='inpmax' value={data.explain} placeholder='请输入活动说明' onChange={(e) => {
						SetDataValue('explain', e.target.value);
					}} />
				</Infocontainer> */}
				{/* 报名自定义信息 */}
				<GroupTitle title='报名自定义信息' />
				<div className='custom' onClick={() => {
					if (newid) {
						window.location.href =
							`${pages['/registrationinfoset']}?aid=${newid}`;
					}
					else {
						Toast.show({
							content: '请先保存！',
							position: 'center',
							icon: 'fail'
						});
					}
				}}>
					<span className='lbl'>自定义报名数据项</span>
					<img className='img' src='/images/right.png' />
				</div>
				{/* <GroupTitleByupdown title='报名要求' onclick={() => {
					setDirection(!direction);
				}} />
				<div className={direction ? 'cboxup' : 'cboxdown'}> */}
				{/* <Checkbox style={{
						'--icon-size': '1rem',
						'--font-size': '0.875rem'
					}} indeterminate={name} onChange={() => {
						setName(!name);
					}}>姓名必填</Checkbox>
					<Checkbox style={{
						'--icon-size': '1rem',
						'--font-size': '0.875rem'
					}} indeterminate={id} onChange={() => {
						setId(!id);
					}}>身份证号必填</Checkbox>
					<Checkbox style={{
						'--icon-size': '1rem',
						'--font-size': '0.875rem'
					}} indeterminate={phone} onChange={() => {
						setPhone(!phone);
					}}>手机号必填</Checkbox>
					<Checkbox style={{
						'--icon-size': '1rem',
						'--font-size': '0.875rem'
					}} indeterminate={work} onChange={() => {
						setWork(!work);
					}}>工作单位必填</Checkbox>
					<Checkbox style={{
						'--icon-size': '1rem',
						'--font-size': '0.875rem'
					}} indeterminate={snum} onChange={() => {
						setSNum(!snum);
					}}>学号必填</Checkbox> */}
				{/* <Checkbox style={{
						'--icon-size': '1rem',
						'--font-size': '0.875rem'
					}} indeterminate={isTo} onChange={() => {
						setIsTo(!isTo);
					}}>允许转发</Checkbox>
					<Checkbox style={{
						'--icon-size': '1rem',
						'--font-size': '0.875rem'
					}} indeterminate={isCancel} onChange={() => {
						setIsCancel(!isCancel);
					}}>允许取消报名</Checkbox>
				</div> */}
				{/* 按钮 */}
				<div className='btn'>
					<Btn label='保存'
						onClick={async () => {
							await Save();
						}} />
					<Btn label='保存并发布' onClick={async () => {
						//判断是否选择模板
						const d = await smartfetch<R3, Q3>(api['/api/activity/fielddata'], 'get', { aid });
						if (d.data.length > 0) {
							const id = await Save(3);
							if (id) {
								window.location.href = `${pages['/publishresult']}?aid=${id}`;
							}
						}
						else {
							Toast.show({
								content: '请设置报名数据项！',
								position: 'center',
								icon: 'fail'
							});
						}
					}} />
					<Btn label='取消' isRed onClick={() => {
						window.history.back();
					}} />
				</div>
			</Container>
		</MainContainer>
		<style jsx>{`
.inp,.inpmax{
margin: 0 1rem 0.2rem 0;
flex-grow: 1;
font-size: 0.875rem;
color: #000000;
border-color: #D9D9D9;
border-width: 0.0625rem;
border-style: solid;
}
.inpmax{
height: 5.3125rem;
word-wrap:break-word;
word-break:normal;
}
.custom{
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
margin:0 1rem 0 2.5rem;
}
.lbl{
font-size: 0.875rem;
color: #505D68;
text-shadow: 0rem 0.25rem 0.25rem rgba(0, 0, 0, 0.25);
text-align: end;
}
.img{
height: 0.875rem;
 width: 0.5rem;
}
.img1{
width: 0.875rem;
 height: 0.5rem;
z-index: 1;
}
.requirement{
display: flex;
flex-direction: row;
justify-content: flex-end;
padding-right: 1.8rem;
margin-bottom: -2rem;
background-color: red;
}

.cboxup,.cboxdown{
display: flex;
flex-direction: column;
margin-left: 1rem;
}
.cboxup{
display:none
}
.cboxdown{
display: flex;
}

.btn{
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
margin-top: 0.5rem;
}
			`}</style>
	</>;
}

/**
 * 日期
 * @param start 
 * @param end 
 * @returns 
 */
function DateComper(start: number | Date | string, end: number | Date | string) {
	const s = new Date(start).valueOf();
	const e = new Date(end).valueOf();
	if (s < e) {
		return false;
	}
	return true;
}

